<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="子公司名称">
                <a-input v-model="queryParam.name" placeholder="" :allowClear="true" />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
              <a-form-item label="地区">
                <a-cascader 
                  v-model="queryParam.address"
                  :options="cityArr" 
                  placeholder="地区"  
                  :fieldNames="{label:'name',children:'children',value:'name'}"/>
              </a-form-item>
              </a-col>
              
            </template>
            <a-col :md="(!advanced && 8) || 24" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button
                  style="margin-left: 8px"
                  @click="() => ((this.queryParam = {}), this.$refs.table.refresh(true))"
                  >重置</a-button
                >
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>
      <!-- :scroll="{ x: true }" -->
      <s-table ref="table" size="default" rowKey="id" :columns="columns" :data="loadData" showPagination="auto" :scroll="{ x: 'auto' }">
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleDel(record)">删除</a>
          </template>
        </span>
        
        <span slot="address" slot-scope="text, scope">
          <span>{{ `${scope.country}-${scope.province}-${scope.city}` }}</span>
        </span>
        <span slot="remark" slot-scope="text">
          <div class="remark-wrap">{{text}}</div>
        </span>
      </s-table>
      <sub-corporation-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :country="country"
        :provinceArr="provinceArr"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <!-- <step-by-step-modal ref="modal" @ok="handleOk" /> -->
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import cloneDeep from 'lodash.clonedeep'
import { STable, Ellipsis } from '@/components'
import { filialeAdd, filialeList, filialeUpdate, levelList } from '@/api/system'
import SubCorporationForm from './modules/subCorporationForm'
import { colors, eachMap } from '@/utils/other'
import { provinceArr } from '@/utils/ccity'
import { country } from '@/utils/country'
import { cityArr } from '@/utils/ccity'
import { Cascader } from 'ant-design-vue'

// import StepByStepModal from './modules/StepByStepModal'
const columns = [
  // id、名称、地区、描述、人数、添加人、添加时间、最后编辑人、最后编辑时间
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    fixed: true,
  },
  {
    title: '名称',
    dataIndex: 'name',
    width: '200px',
    fixed: true,
  },
  {
    title: '地区',
    dataIndex: 'city',
    width: '150px',
    scopedSlots: { customRender: 'address' },
  },

  {
    title: '描述',
    dataIndex: 'remark',
    scopedSlots: { customRender: 'remark' },
  },
  {
    title: '人数',
    dataIndex: 'teamUser',
    sorter: true,
     width:'80px',
    key: 'teamUser',
  },
  
  {
    title: '添加人',
    dataIndex: 'addUserName',
    key: 'addUserName',
     width:'100px',
    customRender: (text) => text || '--',
  },
  {
    title: '添加时间',
    dataIndex: 'addTime',
    key: 'addTime',
    width:'180px',
    customRender: (text) => text || '--',
  },
  {
    title: '最后编辑人',
    dataIndex: 'lastUpdateUserName',
    key: 'lastUpdateUserName',
     width:'120px',
    customRender: (text) => text || '--',
  },
  {
    title: '最后编辑时间',
    dataIndex: 'lastUpdateTime',
    key: 'lastUpdateTime',
     width:'180px',
    customRender: (text) => text || '--',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' },
  },
]

let countryArr = country.map((v) => {
  return {
    name: v.chinese_name,
  }
})

export default {
  name: 'AMW-SubCorporation',
  components: {
    STable,
    Ellipsis,
    SubCorporationForm,
    'a-cascader': Cascader,
  },
  data() {
    this.columns = columns
    return {
      cityArr,
      provinceArr: provinceArr,
      country: countryArr,
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      parameter: {
        pageNum: 1,
        pageSize: 10,
      },
      levelArr: [],
      queryParam: {
        country: '中国',
      },
      data: [],
      sortJ: {
        levelNum: 'level_num',
        teamUser: 'team_user',
        projectNum: 'project_num',
      },
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        let sortJ = this.sortJ
        if (parameter.sortField) {
          parameter.sortJ = sortJ
        }
        let queryParam = cloneDeep(this.queryParam)
        let { address } = queryParam
        if(address){
          queryParam.country = address[0]
          queryParam.province = address[1]
          queryParam.city = address[2]
          delete queryParam.address
        }
        const requestParameters = Object.assign({}, parameter, queryParam)
        return filialeList(requestParameters).then((res) => {
          let result = {
            data: res.data.data,
            pageNo: parameter.pageNo,
            pageSize: parameter.pageSize,
            totalCount: res.data.total,
            totalPage: res.data.pages,
          }
          return result
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
    }
  },

  created() {
    // let query = this.$route.query
    // this.queryParam = {...this.queryParam, ...query}
    // getRoleList({ t: new Date() })
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
      }
    },
    c_cityArr: function () {
      let provinceArr = cloneDeep(this.provinceArr)
      let queryParam = cloneDeep(this.queryParam)
      if (queryParam.province) {
        let i = provinceArr.findIndex((v) => v.name == queryParam.province)
        return provinceArr[i].cityList
      } else {
        return []
      }
    },
  },
  methods: {
    handleChangeQueryParam(){
      delete this.queryParam.city
    },
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    saveCB() {
      const form = this.$refs.createModal.form
      this.visible = false
      this.confirmLoading = false
      // 重置表单数据
      form.resetFields()
      // 刷新表格
      this.$refs.table.refresh()
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          if(values.address){
            values.country = values.address[0]
            values.province = values.address[1]
            values.city = values.address[2]
            delete values.address
          }
          if (values.id > 0) {
            filialeUpdate(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('修改成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          } else {
            delete values.id
            filialeAdd(values)
              .then((res) => {
                this.saveCB()
                this.$message.success('新增成功!')
              })
              .catch((err) => {
                this.saveCB()
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${record.no} 订阅成功`)
      } else {
        this.$message.error(`${record.no} 订阅失败，规则已关闭`)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    handleDel(a_record) {
      let self = this
      const modal = this.$confirm({
        title: '子公司删除',
        content: `是否删除子公司:${a_record.name}`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => self.handleDelete(a_record.id, modal),
        onCancel: () => {},
      })
    },
    handleDelete(a_id, a_modal) {
      return new Promise((resolve, reject) => {
        let data = { id: a_id, status: -1 }
        studioUpdate(data)
          .then((res) => {
            this.$refs.table.refresh()
            this.$message.success('删除成功!')
            resolve()
          })
          .catch((err) => {
            a_modal.destroy()
            this.$message.error('操作失败!')
          })
      })
    },
  },
}
</script>

 